package org.wangp.gateway.sc.web.filter

import com.nimbusds.jose.JWSObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono

/**
 * @author wangpeng (๑•ᴗ•๑)
 * @since 2021/10/6 17:36
 */
@Order(0)
@Component
class AuthGlobalFilter : GlobalFilter {

	companion object {
		val log: Logger = LoggerFactory.getLogger(AuthGlobalFilter::class.java)
	}

	override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
		exchange.request.headers.getFirst("Authorization")?.let {
			val realToken = it.replace("Bearer ", "")
			val jwsObject = JWSObject.parse(realToken)
			val userStr = jwsObject.payload.toString()
			log.info("userStr:${userStr}")
			val request = exchange.request.mutate().header("user", userStr).build()
			return chain.filter(exchange.mutate().request(request).build())
		}
		return chain.filter(exchange)
	}
}
